package boot.spring.controller;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.FormService;
import org.activiti.engine.HistoryService;
import org.activiti.engine.IdentityService;
import org.activiti.engine.ManagementService;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.impl.ProcessEngineImpl;
import org.activiti.engine.impl.context.Context;
import org.activiti.engine.impl.interceptor.Command;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.image.ProcessDiagramGenerator;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.junit.After;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;

import com.alibaba.fastjson.JSON;

import boot.spring.Application;
import boot.spring.service.LeaveService;
import boot.spring.service.SystemService;
import boot.spring.utils.FlowUtils;
import boot.spring.utils.ProcessInstanceDiagramCmd;

@SpringBootTest(classes = { Application.class })
@RunWith(SpringRunner.class)
@WebAppConfiguration
public class testone4 {

	// 流程定义和流程静态资源 activiti的资源管理类
	@Autowired
	RepositoryService rep;
	// 运行时服务，activiti的流程运行管理类
	@Autowired
	RuntimeService runservice;

	// activiti的表单管理类
	@Autowired
	FormService formservice;

	// activiti的用户身份管理类
	@Autowired
	IdentityService identityservice;

	// activiti的任务管理类
	@Autowired
	TaskService taskservice;

	// activiti的历史管理类
	@Autowired
	HistoryService histiryservice;

	@Autowired
	private ProcessEngine processEngine;

	// 是activiti的引擎管理类
	@Autowired
	ManagementService managementService;

	@Autowired
	LeaveService leaveservice;
	@Autowired
	SystemService systemservice;
	
	@Autowired
	FlowUtils flowUtils;
	
	private final String  processInstanceid = "67501";
	
	private final String  starter = "xiaoyi";
	private final String  businessKey = "001";
	private final String  processDefinitionKey = "purchase3";
	private final String money = "10001";
	
	private final String deploymentId = "1";
	
	
	
	// 发布流程
	@Ignore
	@Test
	public void testPubDefinition() {
//	    	InputStream in = this.getClass().getClassLoader().getResourceAsStream("process/helloworld.zip");
//			ZipInputStream zipInputStream = new ZipInputStream(in);
		// 1 发布流程
		InputStream inputStreamBpmn = this.getClass().getResourceAsStream("/process/purchase3.bpmn");
		InputStream inputStreamPng = this.getClass().getResourceAsStream("/process/purchase3.png");
		Deployment deploy = rep.createDeployment() // 创建部署对象
				// 使用流的方式部署流程
				.addInputStream("purchase3.bpmn", inputStreamBpmn).addInputStream("purchase3.png", inputStreamPng)
				// 指定资源目录的方式部署流程
//	                .addClasspathResource("process/leave.bpmn")
//					.addClasspathResource("process/leave.png")
				// 使用字符串部署流程
//					.addString("leave.bpmn", "")
				// 使用压缩包的方式部署流程
//					.addZipInputStream(zipInputStream)
				.name("purchase3")// 添加部署的名称
				.deploy();

		System.out.println("----getId---->" + deploy.getId());
		System.out.println("----getCategory---->" + deploy.getCategory());
		System.out.println("----getName---->" + deploy.getName());
		System.out.println("----getTenantId---->" + deploy.getTenantId());
		System.out.println("----getDeploymentTime---->" + deploy.getDeploymentTime());
		System.out.println("----getClass---->" + deploy.getClass());

		/*
		 * Map<String,Object> variables= new HashMap<String,Object>();
		 * variables.put("name","xiaoyi"); variables.put("id","001"); ProcessInstance pi
		 * =
		 * runservice.startProcessInstanceByKey("xiaoyi","xiaoyibusinessKey",variables);
		 * System.out.println("pid:" + pi.getId());
		 */
	}
	
	
	/*
     * 查询流程定义
     */
	@Ignore
    @Test
    public void findProcessDefinition(){
        List<ProcessDefinition> list = processEngine.getRepositoryService()//与流程定义和部署对象相关的Service
                        .createProcessDefinitionQuery()//创建一个流程定义查询
                        /*指定查询条件,where条件*/
                        //.deploymentId(deploymentId)//使用部署对象ID查询
                        //.processDefinitionId(processDefinitionId)//使用流程定义ID查询
                        //.processDefinitionKey(processDefinitionKey)//使用流程定义的KEY查询
                        //.processDefinitionNameLike(processDefinitionNameLike)//使用流程定义的名称模糊查询
                        .processDefinitionKey(processDefinitionKey)
                        /*排序*/
                        .orderByProcessDefinitionVersion().asc()//按照版本的升序排列
                        //.orderByProcessDefinitionName().desc()//按照流程定义的名称降序排列
                        
                        .list();//返回一个集合列表，封装流程定义
                        //.singleResult();//返回唯一结果集
                        //.count();//返回结果集数量
                        //.listPage(firstResult, maxResults)//分页查询
        
        if(list != null && list.size()>0){
            for(ProcessDefinition processDefinition:list){
                System.out.println("流程定义ID:"+processDefinition.getId());//流程定义的key+版本+随机生成数
                System.out.println("流程定义名称:"+processDefinition.getName());//对应HelloWorld.bpmn文件中的name属性值
                System.out.println("流程定义的key:"+processDefinition.getKey());//对应HelloWorld.bpmn文件中的id属性值
                System.out.println("流程定义的版本:"+processDefinition.getVersion());//当流程定义的key值相同的情况下，版本升级，默认从1开始
                System.out.println("资源名称bpmn文件:"+processDefinition.getResourceName());
                System.out.println("资源名称png文件:"+processDefinition.getDiagramResourceName());
                System.out.println("部署对象ID:"+processDefinition.getDeploymentId());
                System.out.println("################################");
            }
        }
        
    }
	 
	/*
     * 查询流程图
     */
    public static int index = 0;
    @After
//    @Test
	public void viewPic() throws IOException{
        /**将生成图片放到文件夹下*/
        Command<InputStream> cmd = new ProcessInstanceDiagramCmd(processInstanceid, runservice, rep, processEngine, histiryservice);
        InputStream in =  managementService.executeCommand(cmd);
//          InputStream in = flowUtils.getResourceDiagramInputStream(processInstanceid);
		  //获取图片的输入流 
//          InputStream in = rep .getResourceAsStream(deploymentId, resourceName);
          String resourceName1 = "购买流程图节点"+index+".png";
          index ++;
		  //将图片生成到D盘的目录下 
          File file = new File(
		  "E:\\ideaworkspace\\Spring-activiti\\src\\test\\java\\boot\\spring\\controller\\"
		  +resourceName1); 
          //将输入流的图片写到D盘下 
          FileUtils.copyInputStreamToFile(in, file);
		 
    }
	// 开始流程
	@Ignore
	@Test
	public void startTask() {
		Map<String,Object> variables = new HashMap<String,Object>();
//		variables.put("starter", starter);
		variables.put("money", money);
		ProcessInstance instance  = runservice.startProcessInstanceByKey(processDefinitionKey, businessKey,variables);
		
		String instanceid = instance.getId();
		System.out.println("----instanceid---->" + instanceid);
	}
	
	// 列出来所有的我发起的任务
	@Ignore
	@Test
	public void listMyTasksWc() {
		List<HistoricTaskInstance> list = histiryservice.createHistoricTaskInstanceQuery().processDefinitionKey(processDefinitionKey)
				.taskAssignee(starter).list();
		
		System.out.println("------历史完成------->"+list.size());
		for (HistoricTaskInstance historicTaskInstance : list) {
			System.out.println("----lishi----->"+historicTaskInstance.getAssignee());;
			System.out.println("----lishi----->"+JSON.toJSONString(historicTaskInstance.getProcessVariables()));
		}
	
	}
	
	
	// 列出来所有的我发起的还没有完成的任务
	@Ignore
	@Test
	public void listMyTasksWfq() {
		List<ProcessInstance> list = runservice.createProcessInstanceQuery().processDefinitionKey(processDefinitionKey).list();
		
		List<Task> list2 = taskservice.createTaskQuery().processDefinitionKey(processDefinitionKey)
//							.processInstanceId(processInstanceid) // 查询一条的
							.processVariableValueLike("starter", starter) //按照发起人的
							.list();
		for (Task task : list2) {
			System.out.println(task.getAssignee());
			System.out.println(task.getId());
		}
		
	}
	// 待我审批或者待我处理的
	@Test
	public void listMyTasksDwsp() {
		
		List<Task> list2 = taskservice.createTaskQuery().processDefinitionKey(processDefinitionKey)
		 			.taskCandidateGroup("采购经理")
		 			.list();
		for (Task task : list2) {
			System.out.println(task.getAssignee());
			System.out.println(task.getId());
		}
		 			
	}
	
	
	// 部门经理审批通过
	@Ignore
	@Test
	public void jinglishenpitongguo() {
		Map<String,Object> variables = new HashMap<String,Object>();
		variables.put("purchaseauditi", true);
		Task task= taskservice.createTaskQuery().processInstanceId(processInstanceid).singleResult();
		taskservice.complete(task.getId(), variables); 
		 
	}
	// 部门经理审批驳回
	@Ignore
	@Test
	public void jinglishenpibohui() {
		Map<String,Object> variables = new HashMap<String,Object>();
		variables.put("purchaseauditi", false);
		ProcessInstance instance  = runservice.startProcessInstanceByKey(processDefinitionKey, businessKey,variables);
		String instanceid = instance.getId();
		System.out.println("----instanceid---->" + instanceid);
	}
	// 财务审批通过
	@Ignore
	@Test
	public void caiwushenpitongguo() {
		Map<String,Object> variables = new HashMap<String,Object>();
		variables.put("finance", true);
		Task task= taskservice.createTaskQuery().processInstanceId(processInstanceid).singleResult();
		taskservice.complete(task.getId(), variables); 
		 
	}
	// 财务审批驳回
	@Ignore
	@Test
	public void caiwushenpibohui() {
		Map<String,Object> variables = new HashMap<String,Object>();
		variables.put("finance", false);
		Task task= taskservice.createTaskQuery().processInstanceId(processInstanceid).singleResult();
		taskservice.complete(task.getId(), variables); 
		 
	}
	
	
	
	// 总经理审批通过
	@Ignore
	@Test
	public void zongjinglishenpitongguo() {
		Map<String,Object> variables = new HashMap<String,Object>();
		variables.put("manager", true);
		Task task= taskservice.createTaskQuery().processInstanceId(processInstanceid).singleResult();
		taskservice.complete(task.getId(), variables); 
		 
	}
	// 总经理审批驳回
	@Ignore
	@Test
	public void zongjinglishenpibohui() {
		Map<String,Object> variables = new HashMap<String,Object>();
		variables.put("manager", false);
		Task task= taskservice.createTaskQuery().processInstanceId(processInstanceid).singleResult();
		taskservice.complete(task.getId(), variables); 
		 
	}
	
	
	
	// 出纳通过
	@Ignore
	@Test
	public void chunashenpitongguo() {
		Map<String,Object> variables = new HashMap<String,Object>();
		
		Task task= taskservice.createTaskQuery().processInstanceId(processInstanceid).singleResult();
		taskservice.complete(task.getId()); 
		 
	}
	
	// 确认收货
	@Ignore
	@Test
	public void benrentongguo() {
		Map<String,Object> variables = new HashMap<String,Object>();
		variables.put("starter", starter);
		Task task= taskservice.createTaskQuery().processInstanceId(processInstanceid).singleResult();
		taskservice.complete(task.getId(), variables); 
		 
	}
	
	
}